<template>
  <div class="ranking-page">
    <!-- 顶部导航栏 -->
    <el-header class="navbar">
      <div class="logo">思不罔学习平台</div>
      <el-menu mode="horizontal" :default-active="activeMenu" @select="handleSelect">
        <el-menu-item index="1" @click="goBackHome">首页</el-menu-item>
        <el-menu-item index="2" @click="goToPersonal">个人中心</el-menu-item>
        <el-menu-item index="3" @click="goToCollection">我的收藏</el-menu-item>
      </el-menu>
      <div class="auth-buttons">
        <el-button v-if="isAdmin" type="text" @click="goToAdmin">管理员入口</el-button>
        <el-button type="text" @click="logout">退出登录</el-button>
      </div>
    </el-header>

    <!-- 切换按钮 -->
    <div class="tab-buttons">
      <el-button
          :type="activeTab === 'user' ? 'primary' : ''"
          @click="activeTab = 'user'"
          class="tab-button"
      >
        <i class="el-icon-user"></i> 用户排行
      </el-button>
      <el-button
          :type="activeTab === 'question' ? 'primary' : ''"
          @click="activeTab = 'question'"
          class="tab-button"
      >
        <i class="el-icon-document"></i> 题目排行
      </el-button>
    </div>

    <!-- 用户排行榜 -->
    <div class="ranking-section" v-show="activeTab === 'user'">
      <el-table
          :data="userRanking"
          style="width: 100%"
          stripe
          border
          v-loading="loading"
          @sort-change="handleSortChange"
      >
        <el-table-column label="排名" align="center" width="80">
          <template #default="{ $index }">
            <div class="rank-cell">
              <span v-if="$index < 3" class="medal-icon">{{ ['🥇', '🥈', '🥉'][$index] }}</span>
              <span v-else>{{ $index + 1 }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" align="center" sortable>
          <template #header>
            <div class="column-header">
              <i class="el-icon-user"></i> 用户名
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="answerCount"
            label="答题数"
            sortable
            align="center"
            :sort-orders="['ascending', 'descending']"
        >
          <template #header>
            <div class="column-header">
              <i class="el-icon-document"></i> 答题数
            </div>
          </template>
          <template #default="{ row }">
            <div class="count-badge">
              <el-tag type="success">{{ row.answerCount }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="correctRate"
            label="正确率"
            sortable
            align="center"
            :sort-orders="['ascending', 'descending']"
        >
          <template #header>
            <div class="column-header">
              <i class="el-icon-success"></i> 正确率
            </div>
          </template>
          <template #default="{ row }">
            <div class="progress-container">
              <el-progress
                  :percentage="row.correctRate"
                  :color="getRateColor(row.correctRate)"
                  :format="(percent) => `${percent}%`"
                  :stroke-width="14"
              />
              <span class="rate-text">{{ row.correctRate }}%</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 用户统计数据卡片 -->
      <div class="stats-container">
        <el-card
            v-for="(stat, index) in userStats"
            :key="index"
            class="stats-card"
            shadow="hover"
            :class="`stat-card-${index}`"
        >
          <div class="stats-icon">
            <i :class="getStatIcon(index)"></i>
          </div>
          <div class="stats-value">{{ stat.value }}</div>
          <div class="stats-title">{{ stat.title }}</div>
        </el-card>
      </div>
    </div>

    <!-- 题目排行榜 -->
    <div class="ranking-section" v-show="activeTab === 'question'">
      <el-table :data="questionRanking" style="width: 100%" stripe border>
        <el-table-column label="排名" width="100" align="center">
          <template #default="{ $index }">
            <div class="rank-cell">
              <span v-if="$index < 3" class="hot-icon">🔥</span>
              <span v-else>{{ $index + 1 }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="题目内容" />
        <el-table-column prop="questionType" label="题型" width="120" align="center">
          <template #default="{ row }">
            <!-- 使用 getQuestionTypeTag 方法 -->
            <el-tag :type="getQuestionTypeTag(row.questionType)">
              {{ getQuestionTypeText(row.questionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="answerTotal" label="作答次数" sortable width="150" align="center">
          <template #default="{ row }">
            <span class="count-text">{{ row.answerTotal }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="correctRate" label="正确率" sortable width="150" align="center">
          <template #default="{ row }">
            <el-progress :percentage="row.correctRate" :color="getRateColor(row.correctRate)" />
          </template>
        </el-table-column>
      </el-table>

      <div class="question-stats">
        <el-card shadow="hover" class="question-stat-card">
          <div id="question-type-chart" style="height: 300px;"></div>
        </el-card>
        <el-card shadow="hover" class="question-stat-card">
          <div id="difficulty-chart" style="height: 300px;"></div>
        </el-card>
      </div>
    </div>

    <!-- 底部 -->
    <div class="footer">
      <div class="footer-column">
        <h3 class="footer-title">思不罔学习平台</h3>
        <p>专注于提供优质在线学习资源，涵盖各类考试题库、学习资料和课程，助力您的学习之路。</p>
      </div>
      <div class="footer-column">
        <h3 class="footer-title">快速链接</h3>
        <ul class="footer-links">
          <li><a href="#">🏠 首页</a></li>
          <li><a href="#">📚 全部课程</a></li>
          <li><a href="#">📝 题库中心</a></li>
          <li><a href="#">🎓 学习路径</a></li>
        </ul>
      </div>
      <div class="footer-column">
        <h3 class="footer-title">学习资源</h3>
        <ul class="footer-links">
          <li><a href="#">📄 学习资料</a></li>
          <li><a href="#">🎮 视频课程</a></li>
          <li><a href="#">📱 移动应用</a></li>
          <li><a href="#">💡 学习技巧</a></li>
        </ul>
      </div>
      <div class="footer-column">
        <h3 class="footer-title">联系我们</h3>
        <ul class="footer-links">
          <li><a href="#">📧 contact@sierwang.com</a></li>
          <li><a href="#">📞 400-123-4567</a></li>
          <li><a href="#">🏢 北京市海淀区科技园</a></li>
        </ul>
      </div>
    </div>
    <div class="copyright">
      © 2023 思而罔学习平台 版权所有 | 京ICP备12345678号
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import router from "@/router";
import { ElMessage } from "element-plus";
import axios from "@/api/server";
import { useUserStore } from '@/store/useUserstore';

const userStore = useUserStore();

const userInfoStr = localStorage.getItem('userInfo');
if (userInfoStr) {
  const userInfo = JSON.parse(userInfoStr);
  userStore.setUserInfo(userInfo);
}

const isAdmin = useUserStore().userInfo.isAdmin;

const activeMenu = ref('1')
const activeTab = ref('user') // 当前激活的标签页

// 用户排行数据
const userRanking = ref([])

// 用户统计
const userStats = ref([
  { title: '总用户数', value: '5,842' },
  { title: '活跃用户', value: '3,215' },
  { title: '平均答题数', value: '456' },
  { title: '平均正确率', value: '76%' }
])

function getStatIcon(index) {
  // 根据 index 返回对应的图标类名
  const iconMap = [
    'el-icon-user',      // 第1个统计项的图标
    'el-icon-star-on',   // 第2个统计项的图标
    'el-icon-s-data',    // 第3个统计项的图标
    'el-icon-s-marketing' // 第4个统计项的图标
  ]
  return iconMap[index] || 'el-icon-question'
}

// 题目排行数据
const questionRanking = ref([])

// 获取正确率颜色
const getRateColor = (rate) => {
  if (rate >= 90) return '#67C23A'
  if (rate >= 70) return '#409EFF'
  if (rate >= 50) return '#E6A23C'
  return '#F56C6C'
}

// 获取题目类型标签
const getQuestionTypeTag = (type) => {
  const typeMap = {
    '单选题': 'success',
    '多选题': 'warning',
    '简答题': 'danger',
    '编程题': 'info',
    'choice': 'success',  // 兼容英文类型
    'fill_in': 'warning'
  }
  return typeMap[type] || ''
}

// 返回显示文本
const getQuestionTypeText = (type) => {
  const textMap = {
    'choice': '选择题',
    'fill_in': '填空题',
    '单选题': '单选题',
    '多选题': '多选题',
    '简答题': '简答题',
    '编程题': '编程题'
  }
  return textMap[type] || type
}

const handleSortChange = ({ column, prop, order }) => {
  if (!prop || !order) return

  userRanking.value.sort((a, b) => {
    // 数值类型排序
    if (prop === 'answerCount' || prop === 'correctRate') {
      return order === 'ascending'
          ? a[prop] - b[prop]
          : b[prop] - a[prop]
    }
    // 字符串类型排序
    return order === 'ascending'
        ? a[prop].localeCompare(b[prop])
        : b[prop].localeCompare(a[prop])
  })
}

// 初始化题目类型图表
const initQuestionTypeChart = () => {
  const chartDom = document.getElementById('question-type-chart')
  if (!chartDom) return

  const chart = echarts.init(chartDom)
  const option = {
    title: {
      text: '题目类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '题目类型',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 45, name: '单选题' },
          { value: 25, name: '多选题' },
          { value: 15, name: '简答题' },
          { value: 10, name: '编程题' },
          { value: 5, name: '其他' }
        ]
      }
    ]
  }
  chart.setOption(option)
}

// 初始化难度图表
const initDifficultyChart = () => {
  const chartDom = document.getElementById('difficulty-chart')
  if (!chartDom) return

  const chart = echarts.init(chartDom)
  const option = {
    title: {
      text: '题目难度分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['简单', '中等', '困难', '极难']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '题目数量',
        type: 'bar',
        data: [120, 80, 45, 15],
        itemStyle: {
          color: (params) => {
            const colorList = ['#95D475', '#5B8FF9', '#F6BD16', '#F4664A']
            return colorList[params.dataIndex]
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 获取排行榜数据
const getRankingData = async () => {
  try {
    // 这里应该是实际的API请求
    const userRes = await axios.get('/users/sort')

    userRanking.value = userRes.data.data.perAnswerList.map(item => ({
      ...item,
      correctRate: parseFloat(item.correctRate) || 0 // 将"100.00%"转为100
    }))

    userStats.value = [
      { title: '平均答题数', value: userRes.data.data.avgAnswerCount },
      { title: '平均正确率', value: userRes.data.data.avgCorrectRate },
      { title: '总用户数', value: userRes.data.data.perAnswerList.length },
      { title: '活跃用户', value: userRes.data.data.perAnswerList.length } // 这里可以根据实际业务调整
    ]

    console.log(userRanking)

    const questionRes = await axios.get('/question/list');
    questionRanking.value = questionRes.data.data.map(item => ({
      ...item,
      // 确保correctRate是数值类型
      correctRate: parseFloat(item.correctRate) || 0
    }));

    // 初始化图表
    nextTick(() => {
      initQuestionTypeChart()
      initDifficultyChart()
    })
  } catch (error) {
    ElMessage.error('获取排行榜数据失败: ' + error.message)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  getRankingData()
})

// 导航方法
const handleSelect = (index) => console.log('当前菜单项：', index)
const goToAdmin = () => router.push('/admin/manage')
const goBackHome = () => router.push('/home')
const goToPersonal = () => router.push('/personal')
const goToCollection = () => router.push('/collection')
const logout = async () => {
  try {
    await axios.post('/users/logout'); // 会自动带上 Bearer token
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    ElMessage.success('退出成功');
    await router.push('/');
  } catch (error) {
    console.error('退出失败：', error);
    ElMessage.error('退出失败');
  }
};
</script>

<style scoped>
.ranking-section {
  margin: 20px 40px;
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.column-header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 15px;
  color: #333;
}

.column-header i {
  margin-right: 8px;
  font-size: 16px;
}

.rank-cell {
  font-weight: bold;
  font-size: 16px;
  display: flex;
  justify-content: center;
}

.medal-icon {
  font-size: 22px;
}

.count-badge {
  display: flex;
  justify-content: center;
}

.progress-container {
  position: relative;
  padding: 0 20px;
}

.rate-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 13px;
  font-weight: 500;
  color: #555;
}

/* 用户统计卡片样式 */
.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  margin-top: 35px;
}

.stats-card {
  text-align: center;
  padding: 25px 15px;
  border-radius: 12px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(119, 186, 243, 0.25);
}

.stats-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #77baf3, #71e1f1);
}

.stats-icon {
  font-size: 32px;
  margin-bottom: 15px;
  color: #77baf3;
}

.stat-card-0 .stats-icon { color: #67C23A; }
.stat-card-1 .stats-icon { color: #409EFF; }
.stat-card-2 .stats-icon { color: #E6A23C; }
.stat-card-3 .stats-icon { color: #F56C6C; }

.stats-value {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 10px;
  color: #333;
}

.stat-card-0 .stats-value { color: #67C23A; }
.stat-card-1 .stats-value { color: #409EFF; }
.stat-card-2 .stats-value { color: #E6A23C; }
.stat-card-3 .stats-value { color: #F56C6C; }

.stats-title {
  color: #666;
  font-size: 15px;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .ranking-section {
    margin: 15px;
    padding: 18px;
  }

  .stats-container {
    grid-template-columns: 1fr;
  }

  .progress-container {
    padding: 0 10px;
  }

  .rate-text {
    font-size: 12px;
  }
}
.ranking-page {
  max-width: 1600px;
  margin: 0 auto;
  padding-bottom: 60px;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 40px;
  background: linear-gradient(135deg, #77baf3 0%, #71e1f1 100%);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  height: 70px;
}

.logo {
  font-size: 24px;
  font-weight: 700;
  color: white;
}

.tab-buttons {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  gap: 20px;
}

.tab-button {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s;
}

.ranking-section {
  margin: 20px 40px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-top: 30px;
}

.stats-card {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(119, 186, 243, 0.3);
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #77baf3;
  margin-bottom: 10px;
}

.stats-title {
  color: #666;
  font-size: 14px;
}

.question-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 30px;
}

.question-stat-card {
  padding: 20px;
  border-radius: 8px;
}

.rank-cell {
  font-weight: bold;
  font-size: 18px;
}

.medal-icon, .hot-icon {
  font-size: 24px;
}

.count-text {
  color: #77baf3;
  font-weight: 600;
}

.footer {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 40px;
  padding: 40px;
  margin-top: 60px;
  border-top: 1px solid #eee;
}

.footer-column {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.footer-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
}

.footer-links {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.footer-links a {
  color: #666;
  text-decoration: none;
  transition: color 0.3s;
}

.footer-links a:hover {
  color: #77baf3;
}

.copyright {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
  border-top: 1px solid #eee;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .footer {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .navbar {
    padding: 0 20px;
    flex-direction: column;
    height: auto;
    padding: 15px 0;
  }

  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }

  .question-stats {
    grid-template-columns: 1fr;
  }

  .footer {
    grid-template-columns: 1fr;
    padding: 30px 20px;
  }
}

@media (max-width: 480px) {
  .stats-container {
    grid-template-columns: 1fr;
  }

  .ranking-section {
    margin: 20px 15px;
    padding: 15px;
  }
}
</style>